package org.jeecg.feishu.api.service.impl;

import org.jeecg.feishu.api.constant.FeishuApiConstants;
import org.jeecg.feishu.api.dto.FeishuRequest;
import org.jeecg.feishu.api.dto.WebAccessToken;
import org.jeecg.feishu.api.dto.WebAccessTokenCondition;
import org.jeecg.feishu.api.dto.WebRefreshTokenCondition;
import org.jeecg.feishu.api.service.FeishuApiService;
import org.jeecg.feishu.api.service.FeishuTokenService;

import org.jeecg.feishu.api.config.FeishuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class FeishuTokenServiceImpl implements FeishuTokenService {

    @Autowired
    private FeishuApiService feishuApiService;
    @Autowired
    private FeishuConfig feishuConfig;

    @Override
    public WebAccessToken getWebAccessToken(WebAccessTokenCondition condition) {
        FeishuRequest<WebAccessTokenCondition, WebAccessToken> request = FeishuRequest.newRequestByApp(FeishuApiConstants.APP_ACCESS_TOKEN_BY_CODE_PATH, "POST", condition, new WebAccessToken());
        try {
            return feishuApiService.send(feishuConfig, request);
        } catch (Exception e) {
            log.error("根据code获取登录用户身份失败", e);
        }
        return null;
    }

    @Override
    public WebAccessToken refreshWebAccessToken(String refreshToken) {
        WebRefreshTokenCondition webRefreshTokenCondition = WebRefreshTokenCondition.builder()
                .grantType(FeishuApiConstants.WEB_TOKEN_GRANT_TYPE_REFRESH)
                .refreshToken(refreshToken).build();
        FeishuRequest<WebRefreshTokenCondition, WebAccessToken> request = FeishuRequest.newRequestByApp(FeishuApiConstants.APP_ACCESS_TOKEN_REFRESH_PATH, "POST", webRefreshTokenCondition, new WebAccessToken());
        try {
            return feishuApiService.send(feishuConfig, request);
        } catch (Exception e) {
            log.error("根据code获取登录用户身份失败", e);
        }
        return null;
    }

	@Override
	public String getAuthUrl(String url) {
		String result = "https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri="+url+"&app_id="+feishuConfig.getAppId();
		return result;
	}
}
